const Router = require('koa-router')
const router = new Router({ prefix: '/api/permission' })
const { Permission, Role } = require('../models/model')

// router.post('/test', async (ctx, next) => {
//   console.log(ctx.request.body)
//   const data = await User.create({
//     username: 'duli',
//     password: '111111'
//   })
//   ctx.status = 200
//   ctx.body = {
//     code: 200,
//     msg: '信息成功',
//     data: data
//   }
// })

router.post('/save', async (ctx, next) => {
  // 新增权限时，先权限表中添加数据，然后查询角色表中角色名为 admin 的数据，更新他们的权限
  const body = ctx.request.body
  const data = await Permission.create({
    name: body.name,
    path: body.path,
    type: body.type,
    basename: body.basename,
    basepath: body.basepath
  })
  if (data) {
    const role = await Role.findAll({
      where: {
        name: 'admin'
      }
    })
    var arr = '[' + JSON.stringify({
      name: body.name,
      path: body.path,
      type: body.type,
    }) + ']'
    for(let i=0;i < role.length;i++) {
      // 根据 permission 字段判断更新的字段内容
      if (role[i].dataValues.permission === '[]') {
        await Role.update({
          permission: arr
        },{
          where: {
            id: role[i].dataValues.id
          }
        })
      } else {
        let per = JSON.parse(role[i].dataValues.permission)
        per.push({
          name: body.name,
          path: body.path,
          type: body.type,
        })
        await Role.update({
          permission: JSON.stringify(per)
        },{
          where: {
            id: role[i].dataValues.id
          }
        })
      }
    }
    ctx.status = 200
    ctx.body = {
      code: 200,
      msg: '新增权限成功',
      data: data
    }
  } else {
    ctx.status = 0
    ctx.body = {
      code: 0,
      msg: '新增权限失败',
      data: data
    }
  }
})


module.exports = router